package com.levi.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shentong
 * @date 2021/10/23 10:41
 * @Description TODO
 */
@Slf4j
@Configuration
public class ApplicationConfig {


    @Bean
    public UserDetailsService myUserDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        String [][] userGroupAndRoles ={
                {"zhangsan","123456","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"lisi","123456","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"wangwu","123456","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"zhaoliu","123456","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
                {"other","123456","ROLE_ACTIVITI_USER","GROUP_otherTeam"},
                {"system","123456","ROLE_ACTIVITI_USER"},
                {"admin","123456","ROLE_ACTIVITI_ADMIN"},
        };
        for (String[] users : userGroupAndRoles) {
            List<String> userList = Arrays.asList(Arrays.copyOfRange(users, 2, users.length));
            log.info("> 注册新用户: {}用户认证: [{}]",users[0],userList);
            inMemoryUserDetailsManager.createUser(new User(users[0],passwordEncoder().encode(users[1]),userList.stream()
                    .map(u ->new SimpleGrantedAuthority(userList.get(0))).collect(Collectors.toList())));
        }


        return inMemoryUserDetailsManager;
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
